import { Login } from "@/api/interface";

import { GlobalStore } from "@/stores";
import { AuthStore } from "@/stores/modules/auth";
import { UserFilled } from "@element-plus/icons-vue";
import type { ElForm, MessageHandler } from "element-plus";
import { useRouter } from "vue-router";
import DialogBox from "../../../components/DialogBox";
import { getHome } from "../../../utils/routerUtil";
import Register from "./register";
import { User } from "@/api/interface/index";
import ResetPassword from "./resetPassword";

const LoginForm = defineComponent({
	setup() {
		type FormInstance = InstanceType<typeof ElForm>;
		const loginFormRef = ref<FormInstance>();
		const globalStore = GlobalStore();
		const authStore = AuthStore();
		const router = useRouter();
		const loading = ref(false);
		const loginRules = reactive({
			username: [{ required: true, message: "请输入用户名", trigger: "change" }],
			password: [{ required: true, message: "请输入密码", trigger: "change" }]
		});
		const loginForm = reactive<Login.ReqLoginForm>({
			username: "",
			password: "",
			rememberUser: globalStore.setting.rememberUser
		});
		const rememberUserChange = (val: any) => {
			globalStore.rememberUser(val);
		};
		onMounted(() => {
			authStore.logout();
			if (import.meta.env.DEV) {
				loginForm.username = "admin";
				loginForm.password = "123456";
			}
			if (globalStore.setting.rememberUser) {
				loginForm.username = globalStore.setting.username;
			}
		});
		// 监听enter事件（调用登录）
		const keyudown = (e: any) => {
			e = window.event || e;
			if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
				console.log("enter login.");
				if (loading.value) return;
				login(loginFormRef.value as FormInstance);
			}
		};
		const login = (formEl: FormInstance) => {
			formEl.validate(async (valid: boolean) => {
				if (!valid) return;
				try {
					loading.value = true;
					const err: MessageHandler | undefined = await authStore.login(loginForm);
					if (err != null) {
						loading.value = false;
						return;
					}
					// 4.跳转到首页
					router.push(getHome());
				} catch (e) {
					console.error(e);
				}
				loading.value = false;
			});
		};

		const registerDialog = reactive({
			visible: false,
			detail: { username: "", password: "" }
		});
		const submitRegister = () => {
			loginForm.username = registerDialog.detail.username;
			loginForm.password = registerDialog.detail.password;
			registerDialog.visible = false;
		};

		const resetPwdDialog = reactive({
			visible: false,
			detail: { username: "", password: "" }
		});
		return () => {
			return (
				<>
					<DialogBox class="register-dialog" hideFooter v-model:visible={registerDialog.visible} title="用户注册" width="1024px">
						{registerDialog.visible ? (
							<Register
								detail={registerDialog.detail as User.ReqUserRegister}
								onBackLogin={() => (registerDialog.visible = false)}
								onSubmit={() => submitRegister()}
							/>
						) : null}
					</DialogBox>
					<DialogBox hideFooter v-model:visible={resetPwdDialog.visible} title="重置密码" width="800px">
						{resetPwdDialog.visible ? <ResetPassword onSubmit={() => (resetPwdDialog.visible = false)} /> : null}
					</DialogBox>
					<el-form model={loginForm} ref={loginFormRef} rules={loginRules} size="large" onKeydown={keyudown}>
						<el-form-item prop="username">
							<el-input class="pb-2" v-model={loginForm.username} placeholder="请输入用户名">
								{{
									prefix: () => {
										return (
											<el-icon class="el-input__icon">
												<user />
											</el-icon>
										);
									}
								}}
							</el-input>
						</el-form-item>
						<el-form-item prop="password" class="el-form-password">
							<el-input
								type="password"
								v-model={loginForm.password}
								placeholder="请输入密码"
								show-password
								autocomplete="new-password"
							>
								{{
									prefix: () => {
										return (
											<el-icon class="el-input__icon">
												<lock />
											</el-icon>
										);
									}
								}}
							</el-input>
						</el-form-item>
						<el-form-item>
							<div class="w-full h-6 flex justify-between">
								<el-checkbox
									v-model={loginForm.rememberUser}
									onChange={rememberUserChange}
									label="记住登录名"
									style="margin-top:-8px;"
								/>
								<el-link type="primary" onClick={() => (resetPwdDialog.visible = true)}>
									忘记密码?
								</el-link>
							</div>
						</el-form-item>
					</el-form>
					<div class="login-btn flex">
						<el-button
							class="flex-1"
							icon={UserFilled}
							onClick={() => login(loginFormRef.value as FormInstance)}
							size="large"
							type="primary"
							loading={loading.value}
						>
							登录
						</el-button>
					</div>
					<div class="flex justify-center login-panel-register">
						<span>没有账号？ </span>
						<el-link type="primary" onClick={() => (registerDialog.visible = true)}>
							立即注册
						</el-link>
					</div>
					<div class="ext-tips">建议使用chrome浏览器获得最佳体验效果</div>
				</>
			);
		};
	}
});
export default LoginForm;
